<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
            <!-- <el-form-item label="是否删除 0：未删除 1：已删除" prop="isDeleted">
              <el-input
                v-model="queryParams.isDeleted"
                placeholder="请输入是否删除 0：未删除 1：已删除"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item> -->
            <el-form-item label="校区名称" prop="name">
                <el-input
                        v-model="queryParams.name"
                        placeholder="请输入校区名称"
                        clearable
                        @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="学校" prop="schoolName">
                <el-input
                        v-model="queryParams.schoolName"
                        placeholder="请输入学校"
                        clearable
                        @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="所在省" prop="provinceName">
                <el-select v-model="queryParams.provinceId" filterable placeholder="请选择省份"
                           @change="provinceChange">
                    <el-option
                            v-for="item in provinceOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="所在市" prop="cityName">
                <el-select v-model="queryParams.cityId" filterable placeholder="请选择市" @change="cityChange">
                    <el-option
                            v-for="item in cityOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="所在区" prop="regionName">
                <el-select v-model="queryParams.regionId" filterable placeholder="请选择区">
                    <el-option
                            v-for="item in regionOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="详细地址" prop="address">
                <el-input
                        v-model="queryParams.address"
                        placeholder="请输入详细地址"
                        clearable
                        @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" size="small" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" size="small" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        size="small"
                        @click="handleAdd"
                        v-hasPermi="['shm:campus:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="Edit"
                        size="small"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['shm:campus:edit']"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        size="small"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['shm:campus:remove']"
                >删除
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="Download"
                        size="small"
                        @click="handleExport"
                        v-hasPermi="['shm:campus:export']"
                >导出
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="campusList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="学校" align="center" prop="schoolName"/>
            <el-table-column label="校区名称" align="center" prop="name"/>
            <el-table-column label="所在省" align="center" prop="provinceName"/>
            <el-table-column label="所在市" align="center" prop="cityName"/>
            <el-table-column label="所在区" align="center" prop="regionName"/>
            <el-table-column label="详细地址" align="center" prop="address"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button
                            size="small"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleUpdate(scope.row)"
                            v-hasPermi="['shm:campus:edit']"
                    >修改
                    </el-button>
                    <el-button
                            size="small"
                            type="text"
                            icon="el-icon-delete"
                            @click="handleDelete(scope.row)"
                            v-hasPermi="['shm:campus:remove']"
                    >删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
                v-show="total>0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
        />

        <!-- 添加或修改校区对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="学校" prop="schoolId">
                    <el-select v-model="form.schoolId" filterable placeholder="请选择学校">
                        <el-option
                                v-for="item in schoolOptions"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="校区名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入名称"/>
                </el-form-item>
                <el-form-item label="地区">
                    <el-cascader v-model="province_city_area" @change="areaChange" :options="areaItemVoOptions"
                                 clearable></el-cascader>
                </el-form-item>
                <el-form-item label="详细地址" prop="address">
                    <el-input v-model="form.address" placeholder="请输入详细地址"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {campusVoList, getCampus, delCampus, addCampus, updateCampus} from "@/api/schoolMessage/campus";
import {listSchool} from "@/api/schoolMessage/school";
import provinceCityRegionApi from "@/api/schoolMessage/provinceCityRegion";
import school from "@/views/schoolMessage/school/index.vue";

export default {
    name: "Campus",
    computed: {
        school() {
            return school
        }
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 校区表格数据
            campusList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                isDeleted: null,
                name: null,
                provinceId: null,
                cityId: null,
                regionId: null,
                address: null,
                schoolId: null
            },
            // 学校的查询参数
            schoolQueryParams: {
                pageNum: 1,
                pageSize: -1,
            },
            // 表单参数
            form: {},
            // 学校选择数组
            schoolOptions: [],
            province_city_area: [],
            // 存储省市区的树形结构数据
            areaItemVoOptions: [],
            provinceOptions: [],
            cityOptions: [],
            regionOptions: [],
            // 表单校验
            rules: {
                name: [
                    {required: true, message: "名称不能为空", trigger: "blur"}
                ],
                provinceId: [
                    {required: true, message: "所在省不能为空", trigger: "blur"}
                ],
                cityId: [
                    {required: true, message: "所在市不能为空", trigger: "blur"}
                ],
                regionId: [
                    {required: true, message: "所在区不能为空", trigger: "blur"}
                ],
                address: [
                    {required: true, message: "详细地址不能为空", trigger: "blur"}
                ],
                schoolId: [
                    {required: true, message: "学校不能为空", trigger: "blur"}
                ]
            }
        };
    },
    created() {
        this.getList();
        this.getSchoolList();
        this.getAreaTree();
        this.selectProvince();
        this.selectCity();
        this.selectRegion();
    },
    methods: {
        /** 查询校区列表 */
        getList() {
            this.loading = true;
            campusVoList(this.queryParams).then(response => {
                // console.log("response:" + JSON.stringify(response))
                this.campusList = response.rows;
                // console.log("this.campusList:" + JSON.stringify(this.campusList))
                this.total = response.total;
                this.loading = false;
            });
        },
        getSchoolList() {
            listSchool(this.schoolQueryParams).then(res => {
                // console.log("listSchoolRes:" + JSON.stringify(res));
                this.schoolOptions = res.rows;
            })
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                createTime: null,
                updateTime: null,
                isDeleted: null,
                name: null,
                provinceId: null,
                cityId: null,
                regionId: null,
                address: null,
                schoolId: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加校区";
            // console.log(1)
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids
            getCampus(id).then(response => {
                this.form = response.data;
                this.province_city_area.push(this.form.provinceId);
                this.province_city_area.push(this.form.cityId);
                this.province_city_area.push(this.form.regionId);
                this.open = true;
                this.title = "修改校区";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        updateCampus(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addCampus(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.province_city_area = [];
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除校区编号为"' + ids + '"的数据项？').then(function () {
                return delCampus(ids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('shm/campus/export', {
                ...this.queryParams
            }, `campus_${new Date().getTime()}.xlsx`)
        },
        /**
         * 获取省市区树形结构数据
         */
        getAreaTree() {
            provinceCityRegionApi.getAreaTree().then(res => {
                // console.log("provinceCityRegionApi.getAreaTree：" + JSON.stringify(res));
                this.areaItemVoOptions = res.data;
            })
        },
        /**
         * 省市区被修改
         */
        areaChange() {
            // console.log("province_city_area:" + this.province_city_area);
            this.form.provinceId = this.province_city_area[0];
            this.form.cityId = this.province_city_area[1];
            this.form.regionId = this.province_city_area[2];
        },
        /**
         * 查询省市区数据
         * @param type 0：省 1：市 2：区
         */
        selectProvinceCityRegion(type) {
            let query = {
                pageNum: 1,
                pageSize: -1,
                type: type
            }
            let isNeedSearchDatabase = true;

            if (type === 1) {
                if (this.queryParams.provinceId != null) {
                    // 省选择好了
                    query.parentId = this.queryParams.provinceId;
                }
            } else if (type === 2) {
                if (this.queryParams.cityId != null) {
                    // 市选择好了
                    query.parentId = this.queryParams.cityId;
                } else if (this.queryParams.provinceId != null) {
                    isNeedSearchDatabase = false;
                    // 省选择好了，市没有选择好
                    provinceCityRegionApi.listRegionByProvinceId(this.queryParams.provinceId).then(
                        res => {
                            // console.log("listRegionByProvinceId:" + JSON.stringify(res.rows));
                            // console.log("区数据发生变化")
                            this.regionOptions = res.rows;
                        }
                    )
                }
            }

            if (isNeedSearchDatabase) {
                provinceCityRegionApi.list(query).then(
                    res => {
                        if (type === 0) {
                            this.provinceOptions = res.rows;
                        } else if (type === 1) {
                            this.cityOptions = res.rows;
                        } else if (type === 2) {
                            this.regionOptions = res.rows;
                        }
                    }
                )
            }

        },
        selectProvince() {
            this.selectProvinceCityRegion(0);
        },
        selectCity() {
            this.selectProvinceCityRegion(1);
        },
        selectRegion() {
            this.selectProvinceCityRegion(2);
        },
        /**
         * 如果选择省份发生了改变
         */
        provinceChange() {
            this.selectProvinceCityRegion(1);
            this.selectProvinceCityRegion(2);
        },
        cityChange() {
            this.selectProvinceCityRegion(2);
        }
    }
};
</script>

